package com.d3works.apps.businessproject.service;

import com.d3works.apps.account.db.AnalyticMoveLine;
import com.d3works.apps.businessproject.service.app.AppBusinessProjectService;
import com.d3works.apps.project.db.Project;
import com.d3works.apps.purchase.db.PurchaseOrder;
import com.d3works.apps.purchase.db.PurchaseOrderLine;
import com.d3works.apps.purchase.db.repo.PurchaseOrderLineRepository;
import com.d3works.apps.sale.db.SaleOrderLine;
import com.d3works.apps.supplychain.service.PurchaseOrderLineServiceSupplychainImpl;
import com.d3works.exception.D3worksException;
import com.d3works.inject.Beans;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import java.util.List;

public class PurchaseOrderLineServiceProjectImpl extends PurchaseOrderLineServiceSupplychainImpl
    implements PurchaseOrderLineProjectService {

  @Inject private PurchaseOrderLineRepository purchaseOrderLineRepo;

  @Override
  public PurchaseOrderLine createPurchaseOrderLine(
      PurchaseOrder purchaseOrder, SaleOrderLine saleOrderLine) throws D3worksException {

    PurchaseOrderLine line = super.createPurchaseOrderLine(purchaseOrder, saleOrderLine);

    if (line != null
        && saleOrderLine != null
        && Beans.get(AppBusinessProjectService.class).isApp("business-project")) {
      line.setProject(saleOrderLine.getProject());
    }

    return line;
  }

  @Transactional
  @Override
  public void setProject(List<Long> purchaseOrderLineIds, Project project) {

    if (purchaseOrderLineIds != null) {

      List<PurchaseOrderLine> purchaseOrderLineList =
          purchaseOrderLineRepo.all().filter("self.id in ?1", purchaseOrderLineIds).fetch();

      for (PurchaseOrderLine line : purchaseOrderLineList) {
        line.setProject(project);
        purchaseOrderLineRepo.save(line);
      }
    }
  }

  @Override
  public PurchaseOrderLine createAnalyticDistributionWithTemplate(
      PurchaseOrderLine purchaseOrderLine) {
    PurchaseOrderLine poLine = super.createAnalyticDistributionWithTemplate(purchaseOrderLine);
    List<AnalyticMoveLine> analyticMoveLineList = poLine.getAnalyticMoveLineList();

    if (poLine.getProject() != null && analyticMoveLineList != null) {
      analyticMoveLineList.forEach(analyticLine -> analyticLine.setProject(poLine.getProject()));
    }
    return poLine;
  }

  @Override
  public PurchaseOrderLine updateAnalyticDistributionWithProject(
      PurchaseOrderLine purchaseOrderLine) {
    for (AnalyticMoveLine analyticMoveLine : purchaseOrderLine.getAnalyticMoveLineList()) {
      analyticMoveLine.setProject(purchaseOrderLine.getProject());
    }
    return purchaseOrderLine;
  }
}
